{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Step 0, Accuracy: 0.0940, Loss: 5.2209\n",
      "Step 100, Accuracy: 0.8620, Loss: 0.2816\n",
      "Step 200, Accuracy: 0.9250, Loss: 0.1722\n",
      "Step 300, Accuracy: 0.9200, Loss: 0.2271\n",
      "Step 400, Accuracy: 0.9480, Loss: 0.1011\n",
      "Step 500, Accuracy: 0.9570, Loss: 0.0910\n",
      "Step 600, Accuracy: 0.9500, Loss: 0.1725\n",
      "Step 700, Accuracy: 0.9580, Loss: 0.0925\n",
      "Step 800, Accuracy: 0.9630, Loss: 0.2119\n",
      "Step 900, Accuracy: 0.9630, Loss: 0.1615\n",
      "Step 1000, Accuracy: 0.9680, Loss: 0.0500\n",
      "Step 1100, Accuracy: 0.9700, Loss: 0.0386\n",
      "Step 1200, Accuracy: 0.9720, Loss: 0.0417\n",
      "Step 1300, Accuracy: 0.9670, Loss: 0.0285\n",
      "Step 1400, Accuracy: 0.9720, Loss: 0.0991\n",
      "Step 1500, Accuracy: 0.9700, Loss: 0.0239\n",
      "Step 1600, Accuracy: 0.9760, Loss: 0.1333\n",
      "Step 1700, Accuracy: 0.9810, Loss: 0.0344\n",
      "Step 1800, Accuracy: 0.9750, Loss: 0.0469\n",
      "Step 1900, Accuracy: 0.9800, Loss: 0.0079\n"
     ]
    }
   ],
   "source": [
    "import tensorflow as tf\n",
    "import numpy as np\n",
    "from tensorflow.keras.utils import to_categorical\n",
    "\n",
    "tf.compat.v1.disable_eager_execution()\n",
    "\n",
    "class MnistData:\n",
    "    def __init__(self):\n",
    "        (self.train_images, self.train_labels), (\n",
    "        self.test_images, self.test_labels) = tf.keras.datasets.mnist.load_data()\n",
    "        # 28 * 28\n",
    "        self.train_images = self.train_images.reshape(-1, 784) / 255.0\n",
    "        self.test_images = self.test_images.reshape(-1, 784) / 255.0\n",
    "        # one-hot \n",
    "        self.train_labels = to_categorical(self.train_labels, num_classes=10)\n",
    "        self.test_labels = to_categorical(self.test_labels, num_classes=10)\n",
    "\n",
    "    def next_batch(self, batch_size):\n",
    "        idx = np.random.choice(len(self.train_images), batch_size)\n",
    "        return self.train_images[idx], self.train_labels[idx]\n",
    "\n",
    "\n",
    "mnist = MnistData()\n",
    "\n",
    "learning_rate = 1e-4\n",
    "keep_prob_rate = 0.7\n",
    "max_epoch = 2000\n",
    "\n",
    "# placeholder\n",
    "xs = tf.compat.v1.placeholder(tf.float32, [None, 784], name='xs')\n",
    "ys = tf.compat.v1.placeholder(tf.float32, [None, 10], name='ys')\n",
    "keep_prob = tf.compat.v1.placeholder(tf.float32, name='keep_prob')\n",
    "\n",
    "# 将输入 reshape 为 [batch_size, 28, 28, 1]\n",
    "x_image = tf.reshape(xs, [-1, 28, 28, 1])\n",
    "\n",
    "\n",
    "def weight_variable(shape):\n",
    "    initial = tf.random.truncated_normal(shape, stddev=0.1)\n",
    "    return tf.Variable(initial)\n",
    "\n",
    "def bias_variable(shape):\n",
    "    initial = tf.constant(0.1, shape=shape)\n",
    "    return tf.Variable(initial)\n",
    "\n",
    "def conv2d(x, W):\n",
    "    # 每一维度  滑动步长全部是 1， padding 方式 选择 same\n",
    "    # 提示 使用函数  tf.nn.conv2d\n",
    "    return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')\n",
    "\n",
    "\n",
    "def max_pool_2x2(x):\n",
    "    # 滑动步长 是 2步; 池化窗口的尺度 高和宽度都是2; padding 方式 请选择 same\n",
    "    # 提示 使用函数  tf.nn.max_pool\n",
    "    return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding=\"SAME\")\n",
    "\n",
    "# 卷积层 1\n",
    "W_conv1 = weight_variable([7, 7, 1, 32])\n",
    "b_conv1 = bias_variable([32])\n",
    "h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)\n",
    "h_pool1 = max_pool_2x2(h_conv1)\n",
    "\n",
    "# 卷积层 2\n",
    "W_conv2 = weight_variable([5, 5, 32, 64])\n",
    "b_conv2 = bias_variable([64])\n",
    "h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)\n",
    "h_pool2 = max_pool_2x2(h_conv2)\n",
    "\n",
    "# 全连接层 1\n",
    "W_fc1 = weight_variable([7 * 7 * 64, 1024])\n",
    "b_fc1 = bias_variable([1024])\n",
    "h_pool2_flat = tf.reshape(h_pool2, [-1, 7 * 7 * 64])\n",
    "h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1)\n",
    "h_fc1_drop = tf.nn.dropout(h_fc1, rate=1 - keep_prob)\n",
    "\n",
    "# 全连接层 2\n",
    "W_fc2 = weight_variable([1024, 10])\n",
    "b_fc2 = bias_variable([10])\n",
    "prediction = tf.nn.softmax(tf.matmul(h_fc1_drop, W_fc2) + b_fc2)\n",
    "\n",
    "# 交叉熵函数\n",
    "cross_entropy = tf.reduce_mean(-tf.reduce_sum(ys * tf.math.log(prediction), axis=1))\n",
    "\n",
    "train_step = tf.compat.v1.train.AdamOptimizer(learning_rate).minimize(cross_entropy)\n",
    "\n",
    "# 准确率\n",
    "correct_prediction = tf.equal(tf.argmax(prediction, 1), tf.argmax(ys, 1))\n",
    "accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "\n",
    "def compute_accuracy(v_xs, v_ys):\n",
    "    global prediction\n",
    "    y_pre = sess.run(prediction, feed_dict={xs: v_xs, keep_prob: 1.0})\n",
    "    correct_prediction = tf.equal(tf.argmax(y_pre, 1), tf.argmax(v_ys, 1))\n",
    "    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n",
    "    result = sess.run(accuracy, feed_dict={xs: v_xs, ys: v_ys, keep_prob: 1.0})\n",
    "    return result\n",
    "\n",
    "# 训练模型\n",
    "with tf.compat.v1.Session() as sess:\n",
    "    sess.run(tf.compat.v1.global_variables_initializer())\n",
    "\n",
    "    for i in range(max_epoch):\n",
    "        batch_xs, batch_ys = mnist.next_batch(100)\n",
    "        sess.run(train_step, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: keep_prob_rate})\n",
    "\n",
    "        # 每 100 步输出一次准确率\n",
    "        if i % 100 == 0:\n",
    "            acc = compute_accuracy(mnist.test_images[:1000], mnist.test_labels[:1000])\n",
    "            loss = sess.run(cross_entropy, feed_dict={xs: batch_xs, ys: batch_ys, keep_prob: 1.0})\n",
    "            print(f\"Step {i}, Accuracy: {acc:.4f}, Loss: {loss:.4f}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "anaconda-cloud": {},
  "kernelspec": {
   "display_name": "Python (myenv)",
   "language": "python",
   "name": "myenv"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.11.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
